<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="success" size="small" plain v-if="permissionList" icon="el-icon-upload2" @click="handleImport">导 入</el-button>
        <el-button type="warning" size="small" plain v-if="permissionList" icon="el-icon-download" @click="handleExport">导 出</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.expert_delete" @click="handleDelete">删 除</el-button>
      </template>
      <!-- 应急专家表格自定义 -->
      <template slot="ydsglx" slot-scope="scope">
        <div>{{cellChemicals(scope.row)}}</div>
      </template>
    </avue-crud>
    <el-dialog title="数据导入"
               append-to-body
               :visible.sync="excelBox"
               width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :show-file-list="false" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove,getydsglx} from "@/api/emer/expert";
  import {mapGetters} from "vuex";
  import {getToken} from "@/util/auth";
  import {validateEmail,validateTelephone,validateIC,validateDigitTwo} from "@/api/mmhi/validate";

  export default {
    data() {
      return {
        excelBox: false,
        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [{
            label: '表格导入',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '表格导入中，请稍等',
            showFileList: false,
            span: 24,
            propsHttp: {
              fileName: 'file',
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: "/api/emerExpert/expert/import-expert",
            headers: {}
          },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24,
            }
          ]
        },

        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "姓名",
              prop: "xm",
              align: "center",
              search: true,
              rules: [{
                required: true,
                message: "请输入姓名",
                trigger: "blur"
              }]
            },
            {
              label: "性别",
              prop: "xb",
              hide:true,
              align: "center",
              type:"select",
              dicUrl:
                "/api/blade-system/dict/dictionary?code=sex",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType:"number",
              rules: [{
                required: true,
                message: "请选择性别",
                trigger: "blur"
              }]
            },
            {
              label: "出生年月",
              prop: "csny",
              hide:true,
              align: "center",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              rules: [{
                required: true,
                message: "请输入出生年月",
                trigger: "blur"
              }]
            },
            {
              label: "身份证号码",
              prop: "sfzhm",
              hide:true,
              align: "center",
              rules: [{
                required: true,
                validator: validateIC,
                trigger: "blur"
              }]
            },
            {
              label: "政治面貌",
              prop: "zzmm",
              hide:true,
              align: "center",
              type:"select",
              dicUrl:
                "/api/blade-system/dict-biz/dictionary?code=emer_expert_zzmm",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入政治面貌",
                trigger: "blur"
              }]
            },
            {
              label: "工作单位",
              prop: "gzdw",
              align: "center",
              rules: [{
                required: true,
                message: "请输入工作单位",
                trigger: "blur"
              }]
            },
            {
              label: "地址",
              prop: "dz",
              width:"150px",
              align: "center",
              rules: [{
                required: true,
                message: "请输入地址",
                trigger: "blur"
              }]
            },
            {
              label: "毕业院校",
              prop: "byyx",
              hide:true,
              align: "center",
              rules: [{
                required: true,
                message: "请输入毕业院校",
                trigger: "blur"
              }]
            },
            {
              label: "最高学历",
              prop: "zgxl",
              hide:true,
              align: "center",
              type:"select",
              dicUrl:
                "/api/blade-system/dict-biz/dictionary?code=emer_expert_zgxl",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入最高学历",
                trigger: "blur"
              }]
            },
            {
              label: "工作年限",
              prop: "gznx",
              hide:true,
              align: "center",
              rules: [{
                required: true,
                validator: validateDigitTwo,
                trigger: "blur"
              }]
            },
            {
              label: "联系电话（区号-电话号码）",
              prop: "lxdh",
              align: "center",
              width:"180px",
              rules: [{
                required: true,
                validator: validateTelephone,
                trigger: "blur"
              }]
            },
            {
              label: "手机号码",
              prop: "sj",
              align: "center",
              width:"100px",
              rules: [{
                required: true,
                validator: validateTelephone,
                trigger: "blur"
              }]
            },
            {
              label: "职务",
              prop: "zw",
              align: "center",
              rules: [{
                required: true,
                message: "请输入职务",
                trigger: "blur"
              }]
            },
            {
              label: "职称",
              prop: "zc",
              align: "center",
              type:"select",
              dicUrl:
                "/api/blade-system/dict-biz/dictionary?code=emer_expert_zc",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入职称",
                trigger: "blur"
              }]
            },
            {
              label: "专业",
              prop: "zy",
              align: "center",
              rules: [{
                required: true,
                message: "请输入专业",
                trigger: "blur"
              }]
            },
            {
              label: "应急专长",
              prop: "yjzc",
              align: "center",
              rules: [{
                required: true,
                message: "请输入应急专长",
                trigger: "blur"
              }]
            },
            {
              label: "专家类别",
              prop: "zjlb",
              align: "center",
              search: true,
              type:"select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_expert_zjlb",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入专家类别",
                trigger: "blur"
              }]
            },
            {
              label: "电子邮件",
              prop: "dzyj",
              width:160,
              align: "center",
              rules: [{
                required: true,
                validator: validateEmail,
                trigger: "blur"
              }]
            },
            {
              label: "应对事故类型",
              prop: "ydsglx",
              multiple: true,
              slot: true,
              align: "center",
              width:"180px",
              type: "tree",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_eqpt_yjsglx",
              props: {
                label: "dictValue",
                value: "dictKey",
              },
              checkStrictly: true,
              rules: [{
                required: true,
                message: "请输入应对事故类型",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "bz",
              align: "center",
              type: "textarea",
              maxlength:500,
              span: 24,
              minRows: 6,
              hide: true,
              rules: [{
                required: false,
                message: "请输入备注",
                trigger: "blur"
              }]
            },
            {
              label: "企业id",
              prop: "bladeDeptId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "租户id",
              prop: "tenantId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建人",
              prop: "createUser",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建部门",
              prop: "createDept",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建时间",
              prop: "createTime",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
          ]
        },
        data: [],
        // 应对事故类型
        ydsglxList: {}
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.expert_add, false),
          viewBtn: this.vaildData(this.permission.expert_view, false),
          delBtn: this.vaildData(this.permission.expert_delete, false),
          editBtn: this.vaildData(this.permission.expert_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },

    mounted() {
      this.initData();
    },
    methods: {

      // 初始化数据
      initData() {
        this.getydsglx();
      },
      // 获取应对事故类型列表
      getydsglx() {
        getydsglx().then(res => {
          this.ydsglxList = {};
          res.data.data.forEach(item => {
            this.ydsglxList[item.dictKey] = item.dictValue;
          });
        })
      },
      // 显示应对事故类型列
      cellChemicals(row) {
        if(row.ydsglx === undefined || typeof row.ydsglx === "object") {
          return "";
        }
        var arr = row.ydsglx.split(",");
        var faults = [];
        for(let i = 0 ; i < arr.length ; i++) {
          var fault = this.ydsglxList[arr[i]] === undefined ? arr[i] : this.ydsglxList[arr[i]];
          faults.push(fault);
        }
        return faults.join(",");
      },
      // 弹出导入框
      handleImport() {
        this.excelBox = true;
      },

      // 导入前判断
      beforeUpload(file, done, loading) {
        this.isFailed = false;
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        const extension = testmsg === 'xls'
        const extension2 = testmsg === 'xlsx'
        if(!extension && !extension2) {
          this.$message.warning('请上传 .xls,.xlsx 标准格式文件!');
          loading()
        } else {
          done()
        }
      },

      // 导入失败后
      uploadError(error, column) {
        console.log(error,column);
        this.isFailed = true;
      },

      // 导入成功后
      uploadAfter(res, done, loading, column) {
        window.console.log(column);
        this.excelBox = false;
        this.refreshChange();
        done();
      },

      // 取消
      cancle() {
        this.page.currentPage = 1;
        this.onLoad(this.page);
      },
      handleTemplate() {
        window.open(`/api/emerExpert/expert/export-template?${this.website.tokenHeader}=${getToken()}`);
      },
      handleExport() {
        this.$confirm("是否导出应急专家信息?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.open(`/api/emerExpert/expert/export-expert?${this.website.tokenHeader}=${getToken()}`);
        });
      },

      rowSave(row, done, loading) {
        row.ydsglx = typeof row.ydsglx === "object" ? row.ydsglx.join(",") : row.ydsglx;
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        const arr = row.ydsglx.split(",");
        const faults = [];
        for(let i = 0 ; i < arr.length ; i++) {
          const fault = arr[i];
          faults.push(fault);
        }
        row.ydsglx = faults.join(",");
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
